package com.ganmiao.server.user.context;

import com.ganmiao.exception.DefaultBusinessException;
import com.ganmiao.server.sys.vo.SysUserVo;
import com.ganmiao.server.user.vo.MallUserVo;
import org.springframework.core.NamedInheritableThreadLocal;

import java.util.Objects;

/**
 * @author zero.yin
 * @description GrpcContext
 */
public class UserAuthContext implements AutoCloseable {
    private static final ThreadLocal<UserAuthContextHolder> contextThreadLocal = new NamedInheritableThreadLocal<>("user-auth-info");

    public UserAuthContext() {
        UserAuthContextHolder holder = new UserAuthContextHolder();
        contextThreadLocal.set(holder);
    }

    public static void init() {
        new UserAuthContext();
    }

    //管理系统用户信息
    public static void setLoginUser(SysUserVo loginUser) {
        contextThreadLocal.get().setLoginUser(loginUser);
    }

    public static SysUserVo getLoginUser() {
        UserAuthContextHolder holder = contextThreadLocal.get();
        return Objects.isNull(holder) ? null : holder.getLoginUser();
    }

    public static void setMallUser(MallUserVo mallUserVo) {
        contextThreadLocal.get().setMallUser(mallUserVo);
    }

//    public static void setRiderUser(RiderLoginVo riderUser) {
//        contextThreadLocal.get().setRiderUser(riderUser);
//    }

    public static MallUserVo getMallUser() {
        UserAuthContextHolder holder = contextThreadLocal.get();
        return Objects.isNull(holder) ? null : holder.getMallUser();
    }

//    public static RiderLoginVo getRiderUser() {
//        UserAuthContextHolder holder = contextThreadLocal.get();
//        return Objects.isNull(holder) ? null : holder.getRiderUser();
//    }

    /**
     * 系统编码
     */
    public static void setSysCode(String sysCode) {
        contextThreadLocal.get().setSysCode(sysCode);
    }

    public static String getSysCode() {
        UserAuthContextHolder holder = contextThreadLocal.get();
        return Objects.isNull(holder) ? null : holder.getSysCode();
    }

    public static void clear() {
        contextThreadLocal.remove();
    }

    @Override
    public void close() throws Exception {
        clear();
    }

}
